<?php

namespace api\modules\app\services;

use api\components\DataCenter;
use api\modules\app\models\Unit;
use api\modules\app\models\UnitEvent;
use api\modules\app\models\UnitHistory;
use api\utils\ExportUtil;
use Yii;
use api\components\Common;
use api\modules\app\models\MetaArea;
use yii\db\Query;

class EventService
{
    /**
     * 列表查询
     */
    public function search($params, $count = false, $export = false)
    {
        $db = Yii::$app->get('test_3');
        $query = new Query();
        $query->from('unit_event e')
            ->select(['e.unit_id', 'e.event_id','e.unit_code','u.name','u.event_type1','u.event_type2','u.event_type3','district_code','street_code','grid_code','u.lat','u.lng','u.lat_cd','u.lng_cd','event_type','desc','e.user_name','e.event_time','e.state','u.dep_code','u.address', 'u.community_name as meta_level5_name', 'u.estate_name as meta_level6_name'])
            ->leftJoin('unit u', 'e.unit_code=u.unit_code');

        if (isset($params['unit_code']) && !empty($params['unit_code'])) {
            $query->andWhere(['e.unit_code' => $params['unit_code']]);
        }
        if (isset($params['event_type3']) && !empty($params['event_type3'])) {
            $query->andWhere(['u.event_type3_code' => $params['event_type3']]);
        }
        if (isset($params['dep_code']) && !empty($params['dep_code'])) {
            $query->andWhere(['u.dep_code' => $params['dep_code']]);
        }
        if (isset($params['district_code']) && !empty($params['district_code'])) {
            $query->andWhere(['u.district_code' => $params['district_code']]);
        }
        if (isset($params['meta_level3']) && !empty($params['meta_level3'])) {
            $query->andWhere(['u.district_code' => $params['meta_level3']]);
        }
        if (isset($params['meta_level4']) && !empty($params['meta_level4'])) {
            $query->andWhere(['u.street_code' => $params['meta_level4']]);
        }
        if (isset($params['meta_level5']) && !empty($params['meta_level5'])) {
            $query->andWhere(['u.community_code' => $params['meta_level5']]);
        }
        if (isset($params['meta_level6']) && !empty($params['meta_level6'])) {
            $query->andWhere(['u.estate_code' => $params['meta_level6']]);
        }
        if (isset($params['street_code']) && !empty($params['street_code'])) {
            $query->andWhere(['u.street_code' => $params['street_code']]);
        }
        if (isset($params['state']) && !empty($params['state'])) {
            $query->andWhere(['e.state' => $params['state']]);
        }
        if (isset($params['event_time_start']) && !empty($params['event_time_start']) &&
            isset($params['event_time_end']) && !empty($params['event_time_end'])) {
            $query->andWhere(['between', 'e.event_time', $params['event_time_start'], $params['event_time_end']]);
        }

        if ($count) {
            return $query->count('*', $db);
        }

        if ($export) {
            return $query->limit(1000)->orderBy(['event_time' => SORT_DESC])->all($db);
        }

        //分页
        Common::constructPage($query, $params);

        $result = $query->orderBy(['event_time' => SORT_DESC])->all($db);

        if (!empty($result)) {
            foreach ($result as &$v) {
                $unitType = '';
                if (!empty($v['event_type2'])) {
                    $unitType = $v['event_type2'];
                }
                if (!empty($v['event_type3'])) {
                    $unitType .= '/' . $v['event_type3'];
                }
                $v['unit_type'] = $unitType;
                $v['district'] = MetaArea::findNameByCode($v['district_code']);
                $v['meta_level3_name'] = $v['district'];
                $v['street'] = MetaArea::findNameByCode($v['street_code']);
                $v['meta_level4_name'] = $v['street'];
            }
        }

        return $result;
    }

    /**
     * 导出
     */
    public function export($params) {
        $result = $this->search($params,false,true);
        $header = ['标识码','部件名称','部件类型','管理部门','部件位置','所属区域','案件类型','案件描述','异常上报人','部件上报时间','部件当前状态'];
        $rows = [];
        $index = 0;
        if (!empty($result)) {
            foreach ($result as $v) {
                $unitType = ''; //部件类型
                $area = []; //所属区域
                if (!empty($v['event_type2'])) {
                    $unitType = $v['event_type2'];
                }
                if (!empty($v['event_type3'])) {
                    $unitType .= '/' . $v['event_type3'];
                }

                $district = MetaArea::findNameByCode($v['district_code']);
                $street = MetaArea::findNameByCode($v['street_code']);
                if (!empty($district)) {
                    $area[] = $district;
                }
                if (!empty($street)) {
                    $area[] = $street;
                }
                if ($v['grid_code']) {
                    $area[] = $v['grid_code'];
                }

                $rows[$index][] = $v['unit_code'];
                $rows[$index][] = $v['name'];
                $rows[$index][] = $unitType;
                $rows[$index][] = $v['dep_code'];
                $rows[$index][] = $v['address'];
                $rows[$index][] = implode('/', $area);
                $rows[$index][] = $v['event_type'];
                $rows[$index][] = $v['desc'];
                $rows[$index][] = $v['user_name'];
                $rows[$index][] = $v['event_time'] ? date('Y-m-d H:i:s', $v['event_time']) : '';
                $rows[$index][] = $v['state'] == UnitService::STATE_NORMAL ? '正常' : '异常';

                $index++;
            }
        }

        $filename = 'export_' . date('Y-m-d') . '_' . uniqid() . '.csv';
        $file = ExportUtil::exportCsv($filename, $header, $rows);
        $localPath = '/exportfile/'.date('Y-m-d').'/'.$filename;
        return ['url' => $localPath];

//        if (YII_ENV == 'prod' || YII_ENV == 'uat') {
//            $response = Yii::$app->fileServer->uploadFile($file);
//            @unlink($file->getRealPath());
//        }
//
//        return [
//            'url' => $response['path'] ?? "exportfile/${filename}",
//        ];
    }

    /**
     * 拉取案件 变更部件状态为异常
     */
    public function changeUnNormal() {
        //拉取上报时间10分钟内有标识码的案件
        $currentTime = time();
        $startTime = $currentTime - 600;
        $filter = "channel=eq.paidan&args.chs_unit_code=ex.true&openTS={$startTime}~{$currentTime}";
        $post['index_type'] = 'active';
        $post['table'] = 'area-event';
        $post['limit'] = 100;
        $post['filter'] = $filter;
        $post['sort_by'] = 'data.openTS|asc';
        $dataCenter = new DataCenter();
        $response = $dataCenter->getGenericQuery($post);
        if (!isset($response['data']['messages']) || empty($response['data']['messages'])) {
            return 0;
        }

        $messages = $response['data']['messages'];
        foreach ($messages as $message) {
            if (!isset($message['args']['chs_unit_code']) || empty($message['args']['chs_unit_code'])) {
                continue;
            }

            $unitCode = $message['args']['chs_unit_code'];
            $unit = Unit::find()->where(['unit_code' => $unitCode])->one();
            if (empty($unit)) {
                continue;
            }

            $eventId = $message['data']['eventID'];
            $event = UnitEvent::find()->where(['event_id' => $eventId])->one();

            if (!empty($event)) {
                //已经拉取过
                continue;
            }

            //部件状态改为异常
            $unit->state = UnitService::STATE_UNNORMAL;
            $unit->save();

            $userName = isset($message['args']['chs_executeUser_21']) ? $message['args']['chs_executeUser_21'] : '';
            $unitEventModel = new UnitEvent();
            $unitEventModel->unit_id = $unit->id;
            $unitEventModel->event_id = $eventId;
            $unitEventModel->unit_code = $unitCode;
            $unitEventModel->code = isset($message['args']['chs_code']) ? $message['args']['chs_code'] : '';
            $unitEventModel->name = isset($message['args']['eventName']) ? $message['args']['eventName'] : '';
            $unitEventModel->desc = isset($message['args']['description']) ? $message['args']['description'] : '';
            $unitEventModel->event_type = isset($message['args']['chs_messageType_text']) ? $message['args']['chs_messageType_text'] : '';
            $unitEventModel->event_time = isset($message['data']['openTS']) ? $message['data']['openTS'] : 0;
            $unitEventModel->state = $unit->state;
            $unitEventModel->user_name = $userName;
            $unitEventModel->create_time = $currentTime;
            $unitEventModel->save();

            $options['event_id'] = $eventId;
            $options['history_time'] = $message['data']['openTS'];
            $options['state'] = $unit->state;
            HistoryService::log($unitCode, UnitHistory::TYPE2_EVENT_REPORT, $userName, $options);
        }

        return count($messages);
    }

    /**
     * 拉取案件 变更部件状态为维修中
     */
    public function changeRepair() {
        //拉取上报时间10分钟内有标识码的案件
        $currentTime = time();
        $startTime = $currentTime - 600;
        $filter = "channel=eq.paidan&args.chs_unit_code=ex.true&filingTS={$startTime}~{$currentTime}";
        $post['index_type'] = 'active';
        $post['table'] = 'area-event';
        $post['limit'] = 100;
        $post['filter'] = $filter;
        $post['sort_by'] = 'data.openTS|asc';
        $dataCenter = new DataCenter();
        $response = $dataCenter->getGenericQuery($post);
        if (!isset($response['data']['messages']) || empty($response['data']['messages'])) {
            return 0;
        }

        $messages = $response['data']['messages'];
        foreach ($messages as $message) {
            if (!isset($message['args']['chs_unit_code']) || empty($message['args']['chs_unit_code'])) {
                continue;
            }

            $unitCode = $message['args']['chs_unit_code'];
            $unit = Unit::find()->where(['unit_code' => $unitCode])->one();
            if (empty($unit)) {
                continue;
            }

            $eventId = $message['data']['eventID'];
            $event = UnitEvent::find()->where(['event_id' => $eventId])->one();

            if (!empty($event)) {
                if($unit->state == UnitService::STATE_UNNORMAL) {
                    $unit->state = UnitService::STATE_REPAIRING;
                    $unit->save();

                $userName = isset($message['args']['chs_executeUser_23']) ? $message['args']['chs_executeUser_23'] : '';
                    $unitEvent = UnitEvent::findOne(['event_id' => $eventId]);
                    $unitEvent->setAttributes(['state' => UnitService::STATE_REPAIRING]);
                    $unitEvent->save();
                }
                $options['event_id'] = $eventId;
                $options['history_time'] = $message['data']['openTS'];
                $options['state'] = $unit->state;
                HistoryService::log($unitCode, UnitHistory::TYPE2_UNIT_MAINTAIN, $userName, $options);
            }
        }

        return count($messages);
    }

    /**
     * 拉取案件 变更部件状态为正常
     */
    public function changeNormal() {
        //拉取上报时间10分钟内有标识码的案件
        $currentTime = time();
        $startTime = $currentTime - 600;
        $filter = "channel=eq.paidan&args.chs_unit_code=ex.true&closeTS={$startTime}~{$currentTime}";
        $post['index_type'] = 'active';
        $post['table'] = 'area-event';
        $post['limit'] = 100;
        $post['filter'] = $filter;
        $post['sort_by'] = 'data.openTS|asc';
        $dataCenter = new DataCenter();
        $response = $dataCenter->getGenericQuery($post);
        if (!isset($response['data']['messages']) || empty($response['data']['messages'])) {
            return 0;
        }

        $messages = $response['data']['messages'];
        foreach ($messages as $message) {
            if (!isset($message['args']['chs_unit_code']) || empty($message['args']['chs_unit_code'])) {
                continue;
            }

            $unitCode = $message['args']['chs_unit_code'];
            $unit = Unit::find()->where(['unit_code' => $unitCode])->one();
            if (empty($unit)) {
                continue;
            }

            $eventId = $message['data']['eventID'];
            $event = UnitEvent::find()->where(['event_id' => $eventId])->one();

            if (!empty($event)) {
                if($unit->state == UnitService::STATE_REPAIRING) {
                    $unit->state = UnitService::STATE_NORMAL;
                    $unit->save();

                $userName = isset($message['args']['chs_executeUser_10']) ? $message['args']['chs_executeUser_10'] : '';
                    $unitEvent = UnitEvent::findOne(['event_id' => $eventId]);
                    $unitEvent->setAttributes(['state' => UnitService::STATE_NORMAL]);
                    $unitEvent->save();
                }
                $options['event_id'] = $eventId;
                $options['history_time'] = $message['data']['openTS'];
                $options['state'] = $unit->state;
                HistoryService::log($unitCode, UnitHistory::TYPE2_UNIT_COMPLETE, $userName, $options);
            }
        }

        return count($messages);
    }
}